import requests as req
from . import const
import os
import threading

def set_status(status: str):
    return


def set_progress(progress: int):
    return


def set_max(new_max: int):
    return

callback = {
    "setStatus": set_status,
    "setProgress": set_progress,
    "setMax": set_max
}

def install_minecraft_server(version_id, server_dir, call_back=callback):
    URL = "https://bmclapi2.bangbang93.com/version/{VERSION}/{CATEGORY}"
    url = URL.format(VERSION=version_id, CATEGORY="server")
    call_back["setStatus"]("开始下载server端")
    
    try:
        response = req.get(url, headers=const.headers, stream=True)
        response.raise_for_status()
    except req.exceptions.ConnectionError as e:
        call_back["setStatus"]("请求错误: {}".format(e))
        return
    except req.exceptions.RequestException as e:
        call_back["setStatus"]("请求错误: {}".format(e))
        return
    except Exception as e:
        call_back["setStatus"]("未知错误: {}".format(e))
        return
    
    total_size = int(response.headers.get('content-length', 0))
    call_back["setMax"](total_size)
    call_back["setProgress"](0)
    
    file_path = os.path.join(server_dir, version_id, f"server.jar")
    directory = os.path.dirname(file_path)  # 使用 os.path.dirname 获取目录部分
    if not os.path.exists(directory):
        os.makedirs(directory)
    with open(file_path, 'wb') as file:
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:
                file.write(chunk)
                call_back["setProgress"](file.tell())
        # 确保在文件关闭前进行进度检查
        if file.tell() == total_size:
            call_back["setStatus"]("下载完成")
        else:
            call_back["setStatus"]("下载失败")